import React, { useEffect, useState, useCallback, memo, useContext } from 'react'
import { connect } from 'react-redux'
import { getPartitionList, dealVideo } from '@/redux/async'
import { Helmet } from 'react-helmet'
import { setTabindex, ToggleIsdraw } from '@/redux/actions'
import TabBar from 'components/TabBar/TabBar'
import './index.scss'
import Header from 'components/Header/Header'
import Drawer from 'components/Drawer/Drawer'
import VideoItem from 'components/VideoItem/VideoItem'
import classnames from 'classnames'
import Context from '@/config/context'
import { getRankingRegion } from 'api/base'
import Partition from './components/Partition'
import NewestVideo from './components/NewestVideo'
function Channel(props) {
    const { partitions, dispatch, match, isdraw, history } = props

    const [tabBarData, setTabBarData] = useState([])
    const [sectabBar, setSectabBar] = useState([])
    const [curPart, setcurPart] = useState({ name: '', id: '', children: [] })
    const [secPart, setsecPart] = useState()
    const [secIndex, setSecIndex] = useState(0)
    const [mulChild, setMulChild] = useState(false)
    const [recommandVideo, setRecommandVideo] = useState([])
    const [otherVideo, setOtherVideo] = useState([])
    const [tabIndex, setTabIndex] = useState(0)
    const [rId, setRId] = useState(() => match.params.rId)
    useEffect(() => {
        dispatch(getPartitionList())
        setRId(rId)
    }, [rId])
    useEffect(() => {
        let temp = [
            { id: 0, name: '首页', children: [] },
            ...partitions,
            { id: -1, name: '直播', children: [] }
        ]
        setTabBarData(temp)
        setTabbar(temp)
    }, [partitions])
    useEffect(() => {
        getRankingRegion({ rId: rId, day: 7 }).then((res) => {
            setRecommandVideo(dealVideo(res.data.slice(0, 4)))
        })
    }, [rId])
    useEffect(() => {
        const promises = curPart.children.map((item) => {
            return getRankingRegion({ rId: item.id, day: 7 })
        })
        Promise.all(promises).then((results) => {
            let temp = []
            for (let i = 0; i < results.length; i++) {
                const result = results[i]
                const partition = curPart.children[i]
                temp.push({
                    id: partition.id,
                    name: partition.name,
                    videos: dealVideo(result.data.splice(0, 4))
                })
            }
            setOtherVideo(temp)
        })
    }, [curPart])
    const setTabbar = useCallback((data) => {
        let temp = Array.from(data, (x) => {
            return x.id
        })
        let index = temp.indexOf(parseInt(rId))
        if (index >= 0) {
            setcurPart(data[index])
            setTabIndex(index)
            setMulChild(data[index].children.length > 1)
            let sectemp = [{ id: curPart.id || 0, name: '推荐' }, ...data[index].children]
            setSectabBar(sectemp)
            setsecPart(sectemp[0])
        } else {
            let arr = data.map((e) => {
                return Array.from(e.children, (x) => {
                    return x.id
                })
            })
            for (let i in arr) {
                let index = arr[i].indexOf(parseInt(rId))
                if (index >= 0) {
                    setSecIndex(index + 1)
                    setcurPart(data[i])
                    setTabIndex(i)

                    let sectemp = [{ id: curPart.id || 0, name: '推荐' }, ...data[i].children]
                    setSectabBar(sectemp)
                    setsecPart(sectemp[index])
                    return
                }
            }
        }
    })
    const Selecttab = useCallback((tab, index) => {
        dispatch(setTabindex(index))
        judgeTab(tab.id)
    })
    const toggle = useCallback(() => {
        dispatch(ToggleIsdraw())
    })
    const selectSec = useCallback((tab) => {
        history.push({
            pathname: '/channel/' + tab.id
        })
    })
    const getPicUrl = useCallback((url, format) => {
        const picURL = 'http://localhost:3011/transfer/image'
        let suffix = '.jpg'
        // picURL + "?pic=" + url + "@480w_300h.webp"
        return `${picURL}?pic=${url}${format + suffix}`
    })
    const judgeTab = useCallback((id) => {
        if (id === -1) {
            history.push('/live')
            return
        }
        if (id === 0) {
            history.push('/index')
        } else {
            history.push(`/channel/${id}`)
        }
    })
    const goRank = useCallback((data) => {
        history.push({
            pathname: '/ranking/' + data.id
        })
    })
    return (
        <div className="channel">
            <Helmet>
                <title>{curPart.name + (secPart ? '-' + secPart.name : '')}</title>
            </Helmet>
            <div className="top-wrapper">
                <Header />
                <div className="partition flex middle ">
                    <div className="pad-right">
                        <TabBar
                            tabindex={tabIndex}
                            data={tabBarData}
                            type="indicate"
                            Selecttab={Selecttab}
                        ></TabBar>
                    </div>
                    <div
                        className="switch"
                        onClick={() => {
                            toggle()
                        }}
                    >
                        <i className="icon-arrow-down" />
                    </div>
                </div>
                <div className="drawerbox">
                    <Drawer
                        tabindex={tabIndex}
                        isdraw={isdraw}
                        toggle={toggle}
                        data={tabBarData}
                        Selecttab={Selecttab}
                    />
                </div>
                {/* 抽屉 */}
                <div className="secondDraw">
                    {curPart.children.length > 1 ? (
                        <div>
                            <TabBar
                                tabindex={secIndex}
                                data={sectabBar}
                                type={'hightlight'}
                                Selecttab={selectSec}
                            />
                        </div>
                    ) : null}
                </div>
            </div>
            <div className={classnames('line', { barline: curPart.children.length > 1 })}></div>
            <div className="flex recommand middle">
                <div className="title l cell-main">热门推荐</div>
                {mulChild ? (
                    <div
                        className="flex middle"
                        onClick={() => {
                            goRank(curPart)
                        }}
                    >
                        <i className="xxl mr5 icon-ranking" />
                        <span className="l mr5">排行榜</span>
                        <i className="xl mr5 icon-arrow-right" />
                    </div>
                ) : null}
            </div>
            {/* 视频 */}
            <div className="flex middle wrap">
                {recommandVideo.map((video) => {
                    return (
                        <VideoElement
                            getPicUrl={getPicUrl}
                            video={video}
                            show={false}
                            key={video.aId}
                        ></VideoElement>
                    )
                })}
            </div>
            {mulChild === true ? (
                otherVideo.map((partition) => (
                    <Partition
                        data={partition}
                        key={partition.id}
                        getPicUrl={(url, format) => getPicUrl(url, format)}
                    />
                ))
            ) : (
                <NewestVideo id={rId} getPicUrl={(url, format) => getPicUrl(url, format)} />
            )}
        </div>
    )
}
const VideoElement = memo(function showStatistics(props) {
    const { video, getPicUrl, show } = props
    if (!video.pic.includes('@320w_200h')) {
        video.pic = getPicUrl(video.pic, '@320w_200h')
    }
    return <VideoItem video={video} key={video.aId} showStatistics={show} />
})
export default connect(
    function mapStateToProps(state) {
        return state
    },
    function mapDispatchToProps(dispatch) {
        return { dispatch }
    }
)(Channel)
